package de.slothsoft.wasbinich.swingclient.database;

import java.awt.Dimension;
import java.awt.Point;

import de.slothsoft.commons.swing.ButtonType;
import de.slothsoft.commons.swing.WindowUtil;
import de.slothsoft.commons.swing.PreferenceLoginPanel.ExtendedUser;
import de.slothsoft.wasbinich.core.database.DatabaseException;
import de.slothsoft.wasbinich.core.database.DatabaseExceptionCode;
import de.slothsoft.wasbinich.core.database.webservice.AbstractOAuth2Authenticator;
import de.slothsoft.wasbinich.core.database.webservice.RestCommunicator;
import de.slothsoft.wasbinich.swingclient.WasBinIchSwingClient;
import de.slothsoft.wasbinich.swingclient.common.LoginDialog;
import de.slothsoft.wasbinich.swingclient.control.MainPanel;
import de.slothsoft.wasbinich.swingclient.control.WasBinIchLoginDialog;
import de.slothsoft.wasbinich.swingclient.res.Messages;

public class SwingOAuth2Authenticator extends AbstractOAuth2Authenticator {

    private ExtendedUser authenticatedUser;

    public SwingOAuth2Authenticator(RestCommunicator restCommunicator) {
	super(restCommunicator);
    }

    @Override
    protected Token getAccessTokenFromUser() throws DatabaseException {
	WasBinIchLoginDialog dialog = new WasBinIchLoginDialog(null, WasBinIchSwingClient.PREFERENCES,
		this.oAuth2Authenticator);
	center(dialog);
	dialog.setVisible(true);
	if (dialog.getAnswer() == ButtonType.OK) {
	    this.authenticatedUser = dialog.getUser();
	    return dialog.getToken();
	}
	throw new DatabaseException(DatabaseExceptionCode.CANCELLED_BY_USER,
		Messages.getString("LoginBean.tokenCancelledByUser")); //$NON-NLS-1$
    }

    private void center(LoginDialog dialog) {
	MainPanel mainPanel = WasBinIchSwingClient.getMainPanel();
	Dimension size = mainPanel.getSize();
	Point location = mainPanel.getLocationOnScreen();
	WindowUtil.centerWindowOnRectangle(dialog, size.width, size.height, location.x, location.y);
    }

    public ExtendedUser getAuthenticatedUser() {
	return this.authenticatedUser;
    }
}
